package com.zl.csMall.basic.busFile.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zl.csMall.basic.busFile.po.BusFile;
import com.zl.csMall.code.config.token.TokenTriggerAspect;
import com.zl.csMall.basic.busFile.service.BusFileService;
import com.zl.csMall.util.Util;
import com.zl.csMall.vo.ReturnModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;

/**
 * @description: BusFileController
 * @author: ChenNing
 * @date 2025-10-15 15:08
 */
@CrossOrigin(origins = "*")
@Api(tags = "文件")
@RestController
@RequestMapping("csMall/basic/file")
public class BusFileController {

    @Autowired
    private BusFileService busFileService;


    /**
     * @description: 查询全部已上传文件
     * @param name 源文件名
     * @param startDate 保存时间 - 开始
     * @param endDate 保存时间 - 结束
     * @author ChenNing
     * @date: 2025-10-15 16:20
     */
    @TokenTriggerAspect
    @ApiOperation(value = "查询全部已上传文件 - 商家", response = BusFile.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "源文件名"),
            @ApiImplicitParam(name = "startDate", value = "保存时间 - 开始"),
            @ApiImplicitParam(name = "endDate", value = "保存时间 - 结束"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = true),
    })
    @CrossOrigin("*")
    @GetMapping
    public ReturnModel getAll(@RequestHeader(required = false) String token,
                              @RequestParam(name = "name", required = false, defaultValue = "") String name,
                              @RequestParam(name = "startDate", required = false) String startDate,
                              @RequestParam(name = "endDate", required = false) String endDate,
                              @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize){
        LambdaQueryWrapper<BusFile> busFileQuery = new LambdaQueryWrapper<>();
        if (!Util.isNullOrEmpty(startDate) && !Util.isNullOrEmpty(endDate)){
            busFileQuery.between(BusFile::getCreateDate, startDate, endDate);
        }
        busFileQuery.like(BusFile::getOriginalName, name).orderByDesc(BusFile::getCreateDate);
        Page<BusFile> busFilePage = busFileService.page(new Page<>(pageNum, pageSize), busFileQuery);
        return new ReturnModel(busFilePage);
    }

    /**
     * @description: 批量上传文件
     * @author ChenNing
     * @date: 2025-10-15 15:14
     */
    @CrossOrigin("*")
    @ApiOperation(value = "批量上传文件 - 商家")
    @TokenTriggerAspect
    @PostMapping("upload")
    public ReturnModel uploadBatchFile(@RequestHeader(required = false) String token,
                                       @RequestParam("files") MultipartFile[] fileArr){
        if (fileArr == null || fileArr.length < 1){
            return new ReturnModel(false, "请选择文件！");
        }
        long attachmentId = Util.getUuId();
        List<String> pathList = busFileService.saveBatchBusFile(attachmentId, fileArr);
        if (pathList == null){
            return new ReturnModel(false, "文件保存失败！");
        }
        return new ReturnModel(new HashMap(){{
            put("attachmentId", attachmentId);
            put("pathList", pathList);
        }});
    }

    /**
     * @description: 追加附件内的文件
     * @param attachmentId 附件ID
     * @author ChenNing
     * @date: 2025-10-21 10:59
     */
    @CrossOrigin("*")
    @ApiOperation(value = "修改附件文件（追加文件） - 商家")
    @TokenTriggerAspect
    @PutMapping
    public ReturnModel updateFile(@RequestHeader(required = false) String token,
                                  @RequestParam(name = "attachmentId") Long attachmentId,
                                  @RequestParam("files") MultipartFile[] fileArr){
        if (fileArr == null || fileArr.length < 1){
            return new ReturnModel(false, "请选择文件！");
        }
        if (Util.isNullOrEmpty(attachmentId)){
            return new ReturnModel(false, "附件ID为空！");
        }
        boolean isExistence = busFileService.isExistenceToAttachmentId(attachmentId);
        if (!isExistence){
            return new ReturnModel(false, "附件ID不存在！");
        }
        List<String> pathList = busFileService.saveBatchBusFile(attachmentId, fileArr);
        if (pathList != null && pathList.size() > 0){
            return new ReturnModel();
        }
        return new ReturnModel(false, "附件更新失败！");
    }

    /**
     * @description: 下载文件
     * @param busFileId 文件ID
     * @author ChenNing
     * @date: 2025-10-15 16:08
     */
    @CrossOrigin("*")
    @ApiOperation(value = "下载文件")
    @ApiImplicitParam(name = "busFileId", value = "文件ID", required = true)
    @GetMapping("download/{busFileId}")
    public ReturnModel uploadBatchFile(@PathVariable("busFileId") Long busFileId, HttpServletResponse response) throws IOException {
        if (Util.isNullOrEmpty(busFileId)){
            return new ReturnModel(false, "文件ID为空！");
        }
        BusFile busFile = busFileService.getById(busFileId);
        if (busFile == null || busFile.getId() == 0){
            return new ReturnModel(false, "未查询到对应文件！");
        }
        Path filePath = Paths.get(busFile.getPath(), String.valueOf(busFile.getId()));
        if (Files.exists(filePath) && Files.isRegularFile(filePath)) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + busFile.getOriginalName() + "\"");
            try (InputStream inputStream = new FileInputStream(filePath.toFile());
                 OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        }else {
            return new ReturnModel(false, "该文件已被删除！");
        }
        return new ReturnModel();
    }

    /**
     * @description: 根据ID删除文件
     * @param busFileId 文件ID
     * @author ChenNing
     * @date: 2025-10-15 16:14
     */
    @TokenTriggerAspect
    @ApiOperation(value = "删除文件 - 商家")
    @ApiImplicitParam(name = "busFileId", value = "文件ID", required = true)
    @CrossOrigin("*")
    @DeleteMapping("{busFileId}")
    public ReturnModel deleteFile(@RequestHeader(required = false) String token,
                                  @PathVariable("busFileId") Long busFileId){
        if (Util.isNullOrEmpty(busFileId)){
            return new ReturnModel(false, "文件ID为空！");
        }
        boolean result = busFileService.deleteBFile(busFileId);
        if (result){
            return new ReturnModel();
        }
        return new ReturnModel(false, "文件删除失败！");
    }

}
